/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-04-28 11:24:35
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2023-07-27 11:49:56
 * @FilePath: \greenbeeadmin\controllers\admin\admin.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package controllers

import (
	"encoding/json"
	adminService "greenbeeadmin/controllers/admin/service"
	greenbee "greenbeeadmin/controllers/greenbee"
	greenbeeUtils "greenbeeadmin/controllers/greenbee/utils"
	"greenbeeadmin/models"
	"strings"
)

/** 权限管理 **/
// 角色管理列表
type RbacRoleListController struct {
	greenbee.AdminBaseController
}

func (c *RbacRoleListController) Get() {
	c.TplName = "admin/rbac/roleList.html"
}

func (c *RbacRoleListController) Post() {
	var data []models.Role
	page := c.GetString("page", "")
	limit := c.GetString("limit", "")
	searchParam := c.GetString("searchParams", "")

	params := make(map[string]string)
	var roleService adminService.RoleService
	if searchParam != "" {
		bit := []byte(searchParam)
		var searchParams adminService.AdminRoleSearchParams
		json.Unmarshal(bit, &searchParams)
		params["rolename"] = searchParams.Rolename
	}
	if page != "" {
		params["page"] = page
	}
	if limit != "" {
		params["limit"] = limit
	}

	//查询用户数据
	fields := make([]string, 0)
	fields = append(fields, "*")
	data, total_row, err := roleService.GetList(params, fields)
	if err == nil {
		c.SuccessJson(0, data, int(total_row))
	}

	c.ErrorJson(500, "获取失败", 0, data)
}

// 编辑角色 struct
type RbacDelRoleController struct {
	greenbee.AdminBaseController
}

/**
 * @description: 删除角色
 * @return {*}
 */
func (c *RbacDelRoleController) Post() {
	var data interface{}
	ids := c.GetStrings("ids[]")
	id, _ := c.GetInt("id", 0)
	action := c.GetString("action", "")

	var num int64
	var roleService adminService.RoleService
	if action == "dels" {
		//批量删除
		if len(ids) <= 0 {
			c.ErrorJson(500, "参数有误", 0, data)
		}
		num = roleService.RoleDeletes(ids)
	} else {
		//单个删除
		if id == 0 {
			c.ErrorJson(500, "参数有误", 0, data)
		}
		num = roleService.RoleDelete(id)
	}

	c.SuccessJson(0, data, int(num))
}

// 添加角色 struct
type RbacAddRoleController struct {
	greenbee.AdminBaseController
}

// 添加角色页面
func (c *RbacAddRoleController) Get() {
	c.TplName = "admin/rbac/roleAdd.html"
}

// 添加角色
func (c *RbacAddRoleController) Post() {
	var data interface{}
	label := c.GetString("label", "")
	status, _ := c.GetInt("status", 0)
	alias := c.GetString("alias", "")
	remark := c.GetString("remark", "")
	sort, _ := c.GetInt("sort", 0)
	if label == "" {
		c.ErrorJson(500, "角色名不能为空", 0, data)
	}

	//判断角色是否已存在
	var roleService adminService.RoleService
	var role models.Role
	role.Label = label
	field := []string{"Label"}
	_, err := roleService.GetRole(role, field)
	if err == nil {
		c.ErrorJson(500, "'"+label+"' 已存在", 0, data)
	}
	timeFmt := greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", 0)
	role.CreatedAt = timeFmt
	role.UpdatedAt = timeFmt
	role.Status = int8(status)
	role.Alias = alias
	role.Label = label
	role.Remark = remark
	role.Sort = int8(sort)
	id := roleService.RoleAdd(role)
	if id > 0 {
		c.SuccessJson(0, data, 1)
	}
	c.ErrorJson(500, "添加失败", 0, data)

}

// 编辑角色 struct
type RbacEditRoleController struct {
	greenbee.AdminBaseController
}

// 编辑角色 页面
func (c *RbacEditRoleController) Get() {
	id, _ := c.GetInt("id", 0)

	//判断角色是否已存在
	var roleService adminService.RoleService
	var role models.Role
	role.Id = id
	field := []string{"Id"}
	user, err := roleService.GetRole(role, field)
	if err != nil {
		c.Ctx.WriteString("数据有误")
		return
	}
	c.Data["role_user"] = user
	c.TplName = "admin/rbac/roleEdit.html"
}

// 编辑角色
func (c *RbacEditRoleController) Post() {
	var data interface{}
	id, _ := c.GetInt("id", 0)

	label := c.GetString("label", "")
	status, _ := c.GetInt("status", 0)
	alias := c.GetString("alias", "")
	remark := c.GetString("remark", "")
	sort, _ := c.GetInt("sort", 0)

	//判断角色是否存在
	var roleService adminService.RoleService
	var role models.Role
	role.Id = id
	field := []string{"Id"}
	_, err := roleService.GetRole(role, field)
	if err != nil {
		c.ErrorJson(500, "参数有误", 0, data)
	}
	updateField := []string{"Label", "Remark", "Status", "Sort", "Alias"}
	role.Status = int8(status)
	role.Label = label
	role.Remark = remark
	role.Alias = alias
	role.UpdatedAt = greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", 0)
	role.Sort = int8(sort)

	roleService.RoleEdit(role, id, updateField)
	c.SuccessJson(0, data, 1)

}

// 角色权限 struct
type RbacRoleMenuController struct {
	greenbee.AdminBaseController
}

// 角色权限 页面
func (c *RbacRoleMenuController) Get() {
	id, _ := c.GetInt("id", 0)

	//判断角色是否存在
	var roleService adminService.RoleService
	var role models.Role
	role.Id = id
	field := []string{"Id"}
	user, err := roleService.GetRole(role, field)
	if err != nil {
		c.Ctx.WriteString("数据有误")
		return
	}
	c.Data["role_user"] = user
	//查询权限 id

	c.TplName = "admin/rbac/roleMenu.html"
}

// 角色权限 授权提交
func (c *RbacRoleMenuController) Post() {
	var data interface{}
	roleId, _ := c.GetInt("r_id", 0)
	mids := c.GetString("ids", "")
	//判断角色是否存在
	var roleService adminService.RoleService
	var role models.Role
	role.Id = roleId
	field := []string{"Id"}
	_, err := roleService.GetRole(role, field)
	if err != nil {
		c.ErrorJson(500, "参数有误", 0, data)
		return
	}
	// 角色授权
	var ids []string
	if mids != "" {
		ids = strings.Split(mids, ",")
	}
	count := roleService.RoleEmpower(roleId, ids)
	c.SuccessJson(0, data, int(count))
}

// 权限管理 菜单 struct
type RbacMenuController struct {
	greenbee.AdminBaseController
}

// 菜单列表
func (c *RbacMenuController) Get() {
	c.TplName = "admin/rbac/menu.html"
}

// 获取菜单数据
func (c *RbacMenuController) Post() {
	type Datas struct {
		Data    []adminService.TreeAdminMenuData `json:"data"`
		MenuIds []int                            `json:"menu_ids"`
	}
	var data Datas
	roleId, _ := c.GetInt("role_id", 0)
	var menuService adminService.MenuService
	params := make(map[string]string)
	//查询菜单数据
	fields := make([]string, 0)
	fields = append(fields, "*")
	menulist, _ := menuService.GetAdminMenuList(params, fields)
	//数据转为树形结构
	menuTreeList := menuService.GetTreeMenuData(menulist, -1, "")
	data.Data = menuTreeList
	//查询权限节点
	if roleId > 0 {
		var roleService adminService.RoleService
		data.MenuIds = roleService.GetRoleMenusIds(roleId)
	}
	c.SuccessJson(0, data, len(menuTreeList))
}

// 权限管理 删除菜单 struct
type RbacMenuDelController struct {
	greenbee.AdminBaseController
}

// 删除菜单
func (c *RbacMenuDelController) Post() {
	var data interface{}
	id, _ := c.GetInt("id", 0)

	var num int64
	var menuService adminService.MenuService

	if id == 0 {
		c.ErrorJson(500, "参数有误", 0, data)
	}
	// 判断是否存在子菜单
	ChildIds := menuService.GetMenuChildIds(id)
	// 循环删除子菜单
	if len(ChildIds) > 0 {
		for _, cid := range ChildIds {
			num += menuService.DeleteMenu(cid)
		}
	}
	// 删除菜单
	num += menuService.DeleteMenu(id)
	if num > 0 {
		c.SuccessJson(0, data, int(num))
	}
	c.ErrorJson(500, "删除失败", 0, data)
}

// 权限管理 添加菜单 struct
type RbacMenuAddController struct {
	greenbee.AdminBaseController
}

func (c *RbacMenuAddController) Get() {
	var menuService adminService.MenuService
	params := make(map[string]string)
	pid, _ := c.GetInt("parent_id", -1)
	parentAuthority := ""
	if pid > -1 {
		//查询父级菜单数据
		pdata := menuService.GetMenuData(pid)
		parentAuthority = pdata.Authority + "."
	}

	//查询菜单列表数据
	fields := make([]string, 0)
	fields = append(fields, "*")
	menulist, _ := menuService.GetAdminMenuList(params, fields)
	//数据转为树形结构
	menuTreeList := menuService.GetTreeMenuData(menulist, -1, "")
	//fmt.Println(menuTreeList)
	c.Data["menuTreeList"] = menuTreeList
	c.Data["Pid"] = pid
	c.Data["parentAuthority"] = parentAuthority
	c.TplName = "admin/rbac/menuAdd.html"
}

// 添加菜单
func (c *RbacMenuAddController) Post() {
	var data interface{}
	parentId, _ := c.GetInt("parent_id", 0)
	status, _ := c.GetInt("status", 0)
	authorityName := c.GetString("authority_name", "")
	menuIcon := c.GetString("menu_icon", "")
	menuUrl := c.GetString("menu_url", "")
	orderNumber, _ := c.GetInt("order_number", 0)
	authority := c.GetString("authority", "")
	is_menu, _ := c.GetInt("is_menu", 0)

	if parentId == 0 || authorityName == "" {
		c.ErrorJson(500, "参数有误", 0, data)
	}

	var menuService adminService.MenuService
	var menu models.AdminMenu
	timeFmt := greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", 0)
	menu.ParentId = parentId
	menu.CreatedAt = timeFmt
	menu.UpdatedAt = timeFmt
	menu.Status = int8(status)
	menu.Authority = authority
	menu.AuthorityName = authorityName
	menu.MenuIcon = menuIcon
	menu.MenuUrl = menuUrl
	menu.IsMenu = int8(is_menu)
	menu.OrderNumber = orderNumber
	id := menuService.MenuAdd(menu)
	if id > 0 {
		c.SuccessJson(0, data, 1)
	}
	c.ErrorJson(500, "添加失败", 0, data)

}

// 权限管理 编辑菜单 struct
type RbacMenuEditController struct {
	greenbee.AdminBaseController
}

func (c *RbacMenuEditController) Get() {
	id, _ := c.GetInt("id", 0)
	var menuService adminService.MenuService
	params := make(map[string]string)
	//查询菜单数据
	menu := menuService.GetMenuData(id)
	if menu.Id <= 0 {
		c.ErrorJson(500, "参数有误", 0, nil)
	}
	//查询菜单列表数据
	fields := make([]string, 0)
	fields = append(fields, "*")
	menulist, _ := menuService.GetAdminMenuList(params, fields)
	//数据转为树形结构
	menuTreeList := menuService.GetTreeMenuData(menulist, -1, "")
	c.Data["menuTreeList"] = menuTreeList
	c.Data["menu"] = menu
	c.TplName = "admin/rbac/menuEdit.html"
}

// 编辑菜单
func (c *RbacMenuEditController) Post() {
	var data interface{}
	id, _ := c.GetInt("id", 0)
	parentId, _ := c.GetInt("parent_id", 0)
	status, _ := c.GetInt("status", 0)
	authorityName := c.GetString("authority_name", "")
	menuIcon := c.GetString("menu_icon", "")
	menuUrl := c.GetString("menu_url", "")
	orderNumber, _ := c.GetInt("order_number", 0)
	authority := c.GetString("authority", "")
	is_menu, _ := c.GetInt("is_menu", 0)

	if parentId == 0 || authorityName == "" || id == 0 {
		c.ErrorJson(500, "参数有误", 0, data)
	}

	var menuService adminService.MenuService

	// 当前菜单不能选择自己的下级子菜单

	ChildIds := menuService.GetMenuChildIds(id)
	r := greenbeeUtils.InArrayInt(parentId, ChildIds)
	if r {
		c.ErrorJson(500, "不能选择自己的下级子菜单", 0, data)
	}

	var menu models.AdminMenu
	timeFmt := greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", 0)
	menu.Id = id
	menu.ParentId = parentId
	menu.UpdatedAt = timeFmt
	menu.Status = int8(status)
	menu.Authority = authority
	menu.AuthorityName = authorityName
	menu.MenuIcon = menuIcon
	menu.MenuUrl = menuUrl
	menu.IsMenu = int8(is_menu)
	menu.OrderNumber = orderNumber
	updateField := []string{"ParentId", "UpdatedAt", "Status", "Authority", "AuthorityName", "MenuIcon", "MenuUrl", "IsMenu", "OrderNumber"}
	menuService.MenuEdit(menu, id, updateField)

	c.SuccessJson(0, data, 1)

}
